<template>
    <div id="container" class="container"> 

    </div>
</template>

<script setup lang="ts"> 
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { fishWeightApi } from "@/api/fishWeight";

let myChart: echarts.ECharts | null = null;

onMounted(() => { 
var chartDom = document.getElementById('container');
if (chartDom) {
    // 确保容器有尺寸
    chartDom.style.width = '100%';
    chartDom.style.height = '100%';
    
    myChart = echarts.init(chartDom);
    var option;

    fishWeightApi.getLatestRecord().then(res => {
      // 处理数据统计
      const statistics: { [key: string]: number } = {};
      res.data.forEach((item: any) => {
        const fishType = item.recognitionResult || '未识别成功';
        statistics[fishType] = (statistics[fishType] || 0) + 1;
      });

      // 转换为图表需要的格式并限制只显示前5个
      const chartData = Object.entries(statistics)
        .map(([type, count]) => [type, count])
        .sort((a, b) => (b[1] as number) - (a[1] as number)) // 按数量降序排序
        .slice(0, 5); // 只取前5个数据

    option = {
      dataset: [
        {
          dimensions: ['种类', '数量'],
          source: chartData
        },
        {
          transform: {
            type: 'sort',
            config: { dimension: '数量', order: 'desc' } 
          }
        }
      ],
      xAxis: {
        type: 'category',
        axisLabel: { 
          interval: 0, 
          color: 'whitesmoke',
          fontSize: 18
        }
      },
      yAxis: {
        axisLabel: {
          color: 'whitesmoke',
          fontSize: 18
        }
      },
      series: {
        type: 'bar',
        encode: { x: '种类', y: '数量' },
        datasetIndex: 1 // 修改为使用排序后的数据集
      }
    };

    option && myChart.setOption(option);
    
    const handleResize = () => {
        if (myChart) {
            myChart.resize();
        }
    };
    
    window.addEventListener('resize', handleResize);
    
    onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
    });
    
    setTimeout(() => {
        if (myChart) {
            myChart.resize();
        }
    }, 0);
});
}
});

onUnmounted(() => {
    if (myChart) {
        myChart.dispose();
        myChart = null;
    }
});

</script>

<style scoped>
.container{
    width: 100%;
    height: 100%;
}
</style>